package com.jsmile.cloud.msgcenter.zf.strategy.notify;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jsmile.cloud.msgcenter.api.exception.MsgException;
import com.jsmile.cloud.msgcenter.web.config.PayConfig;
import com.jsmile.cloud.msgcenter.zf.enums.AliNotifyTypeEnum;
import com.jsmile.cloud.msgcenter.zf.kit.AliDecodeKit;
import com.jsmile.cloud.msgcenter.zf.req.ali.AliAuthBizContent;
import com.jsmile.cloud.msgcenter.zf.req.ali.AliNotifyResponse;
import com.jsmile.cloud.msgcenter.zf.req.ali.AliPayInfo;
import com.jsmile.cloud.msgcenter.zf.strategy.interfaces.IAlilNotify;

import lombok.extern.slf4j.Slf4j;

/**
 * @author xiao
 * @since 2021/5/30
 */
@Service
@Slf4j
@EnableAsync
public class AuthNotifyStrategy implements IAlilNotify {

    @Autowired
    private AliDecodeKit aliDecodeKit;

    @Override
    public String getNotifyType() {
        return AliNotifyTypeEnum.AUTH.getType();
    }

    /**
     * 授权模板，使用平台第三方的appId
     *
     * @param data
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String excute(String data) {
        log.info("授权回调参数：{}", data);
        // 解析回调消息请求参数
        String requset = data.replace("\\", "").replace("\"{", "{").replace("}\"", "}");
        log.info("转字符串授权回调参数：{}", requset);
        AliNotifyResponse<AliAuthBizContent> notifyResponse = JSON.parseObject(requset, new TypeReference<AliNotifyResponse<AliAuthBizContent>>() {});

        AliPayInfo aliPayInfo = PayConfig.getAliService("");
        // 验签
        aliDecodeKit.checkSign(data, aliPayInfo);
        AliAuthBizContent.Detail detail = notifyResponse.getBizContent().getDetail();
        if (Objects.isNull(detail)) {
            throw new MsgException("未获取到详细信息，请重新授权");
        }
        return SUCCESS;
    }

}
